package com.fingard.dsp.bank.directbank.alipay01;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.HashMap;

/**
 * 支付宝蚂蚁金服渠道对账单下载
 * 
 * @author Cruise
 * @date 2019/3/21
 */
public class ALIPAY01Statement extends ALIPAY01Base implements IStatement {
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();

		String[] unifiedRespHeader = new String[] { "", "" };
		String requestType = getBankConfig().getValueAsString("requestType");
		if ("ftp".equals(requestType.toLowerCase())) {
			unifiedRespHeader = getUnifiedStatementByFTP(p_reqQrySttm, retAts);
		} else {
			unifiedRespHeader = getUnifiedStatementByHttp(p_reqQrySttm, retAts);
		}

		String unifiedTotalNum = retAts.totalNum;

		if ("-1".equals(unifiedRespHeader[0])) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo("统一收单对账单获取失败,原因:" + unifiedRespHeader[1]);
		} else {
			if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");

				String tmpRespInfo = "";
				if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
					tmpRespInfo = unifiedRespHeader[1];
				}
				if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
					tmpRespInfo = "交易为空";
				}
				retAts.writeRespInfo(tmpRespInfo);
			}
			retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(unifiedTotalNum)));
		}

		retAts.writeEnd();
		return retAts;
	}

	/**
	 * 蚂蚁金服渠道支付宝对账单下载
	 */
	public String[] getUnifiedStatementByHttp(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] tmpRespHeader = new String[] { "", "" };

		String tmpRespCode = "";
		String tmpRespInfo = "";

		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "unifiedorder");
			if (actItem != null) {
				String privateKey = actItem.ownKeyStorePath;
				String publicKey = actItem.oppCertFilePath;
				AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId, privateKey, "json", "UTF-8", publicKey, "RSA2");

				WriteBankLogLn("提交银行的地址：" + bankFront.serverURL);

				AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

				String bill_date = Format.Date10Format.format(p_reqQrySttm.getBusDate());
				String json = "{\"bill_type\":\"signcustomer\",\"bill_date\":\"" + bill_date + "\"}";

				WriteBankLogStep2("发送的json数据：" + json);
				request.setBizContent(json);

				AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
				WriteBankLogLn2("银行响应json数据:" + response.getBody());

				if (response.getCode().equals("10000")) {
					bill_date = Format.Date8Format.format(p_reqQrySttm.getBusDate());
					String filePath = createTempFileDirectory() + File.separator + p_reqQrySttm.actNum + "_" + bill_date + ".csv.zip";
					WriteBankLogLn("对账单下载后保存到本地路径:" + filePath);
					
					String url = response.getBillDownloadUrl();
					WriteBankLogLn2("对账单文件下载链接:" + url);
					
					SendBankRespose retResp = smsGet(url, filePath);
					WriteBankLogStep3(retResp);

					// 解析银行返回
					if (retResp.connState == "") {
						String respStr = retResp.retMessage;
						int beginIndex = respStr.indexOf("账务流水号");
						if (beginIndex >= 0) {
							respStr = respStr.substring(beginIndex);
							int endIndex = respStr.indexOf("#-");
							respStr = respStr.substring(0, endIndex);
							WriteBankLogLn("截取后有效对账单明细内容为:\r\n" + respStr);

							StringReader strReader = new StringReader(respStr);
							BufferedReader tmpReader = new BufferedReader(strReader);

							String line1 = tmpReader.readLine();
							String[] columns = line1.split(",");

							while (true) {
								String eachline = tmpReader.readLine();
								if (eachline == null) {
									break;
								}
								String[] values = eachline.split(",");
								if (columns.length == values.length) {
									HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
									RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
									
									String amount = "";
									if (mapKV.containsKey("收入金额（+元）")) {
										amount = mapKV.get("收入金额（+元）").replace("`", "").trim();
										if (Double.parseDouble(amount) > 0) {
											totalNum++;
											
											tmpRetDetail.amount = amount;
											if (mapKV.containsKey("发生时间")) {
												tmpRetDetail.busTime = mapKV.get("发生时间").replace("`", "").replace("-", "").replace(":", "").replace(" ", "").trim();
											}

											if (mapKV.containsKey("商户订单号")) {
												tmpRetDetail.askNumber = mapKV.get("商户订单号").replace("`", "").trim();
											}
											
											if (mapKV.containsKey("商户订单号")) {
												tmpRetDetail.askNumber = mapKV.get("商户订单号").replace("`", "").trim();
											}
											if (mapKV.containsKey("账务流水号")) {
												tmpRetDetail.bkSeq = mapKV.get("账务流水号").replace("`", "").trim();
											}

											if (mapKV.containsKey("业务类型")) {
												tmpRetDetail.busType = mapKV.get("业务类型").replace("`", "").trim();
											}

											if (mapKV.containsKey("备注")) {
												tmpRetDetail.memo = mapKV.get("备注").replace("`", "").trim();
											}

											if (mapKV.containsKey("商品名称")) {
												tmpRetDetail.summary = mapKV.get("商品名称").replace("`", "").trim();
											}
											
											tmpRetDetail.cdFlag = "22";
											tmpRetDetail.transState = TransState.Success;

											retAts.writeRetDetail(tmpRetDetail);
										}
									}
								} else {
									break;
								}
							}
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "交易未生成!";
						}
					} else {
						tmpRespCode = "-1";
						tmpRespInfo = retResp.retMessage;
					}
				} else {
					tmpRespCode = "-1";
					tmpRespInfo = response.getSubMsg();
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);

		tmpRespHeader[0] = tmpRespCode;
		tmpRespHeader[1] = tmpRespInfo;

		return tmpRespHeader;
	}

	/**
	 * 统一收单对账单下载
	 * 
	 * @param p_reqQrySttm
	 * @param retAts
	 * @return
	 * @throws Exception
	 */
	private String[] getUnifiedStatementByFTP(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] tmpRespHeader = new String[] { "", "" };

		String tmpRespCode = "";
		String tmpRespInfo = "";

		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "unifiedorder");
			if (actItem != null) {
				FtpSet ftpSet = bankFront.getFtpSet("unifiedorder");
				WriteBankLogLn2("支付宝统一收单对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);

				String tmpDownFileName = p_reqQrySttm.busDate + "_" + actItem.pid;
				WriteBankLogLn2("支付宝统一收单对账单所在服务器路径:" + StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName + ".zip");

				String tmplocalFileSavePath = createTempFileDirectory() + File.separator + tmpDownFileName + ".zip";
				WriteBankLogLn2("支付宝统一收单对账单文件保存本地路径:" + tmplocalFileSavePath);

				FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
				FtpReceiver ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName + ".zip", tmplocalFileSavePath);
				if (ftpReceiver.isCompleted) {
					WriteBankLogLn("文件下载已完成，开始解压...");
					String tmpLocalDepressDir = getTempFileDirectory();
					ZipUtils.unZip(tmplocalFileSavePath, tmpLocalDepressDir, "GBK");
					// ZipHelper.unzipFile(tmplocalFileSavePath,
					// tmpLocalDepressDir, "GBK");
					WriteBankLogLn("文件解压已完成.");

					String tmpResultFileName = actItem.pid + "_" + p_reqQrySttm.busDate + "_TRADE_DETAILS.csv";
					String tmpResultFilePath = tmpLocalDepressDir + File.separator + tmpResultFileName;
					WriteBankLogLn2("支付宝统一收单对账单结果文件本机路径:" + tmpResultFilePath);

					String tmpStrRet = FileHelper.readFileText(tmpResultFilePath, "GBK");
					WriteBankLogLn2("解压后文件内容为:\r\n" + tmpStrRet);
					if (StringHelper.hasAnyChar(tmpStrRet)) {
						tmpRespCode = "0";

						tmpStrRet = tmpStrRet.substring(tmpStrRet.indexOf("账务流水号"));
						tmpStrRet = tmpStrRet.substring(0, tmpStrRet.indexOf("#"));

						StringReader strReader = new StringReader(tmpStrRet);
						BufferedReader tmpReader = new BufferedReader(strReader);

						String titleLine = tmpReader.readLine();
						String[] columns = titleLine.split(",");

						while (true) {
							String dataLine = tmpReader.readLine();
							if (dataLine == null) {
								break;
							}

							String[] values = dataLine.split(",");
							if (columns.length == values.length) {
								HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);

								String busType = "";
								if (mapKV.containsKey("业务类型")) {
									busType = mapKV.get("业务类型").replace("+", "").replace("-", "").trim();
									if ("收费".equals(busType)) {
										continue;
									}
								}

								totalNum++;

								RetAtsStatementDetail retDetail = new RetAtsStatementDetail();

								if (mapKV.containsKey("发生时间")) {
									retDetail.busTime = mapKV.get("发生时间").replace("`", "").replace("-", "").replace(":", "").replace(" ", "").trim();
								}
								if (mapKV.containsKey("商户订单号")) {
									retDetail.askNumber = mapKV.get("商户订单号").replace("`", "").trim();
								}

								if ("提现".equals(busType)) {
									if (mapKV.containsKey("支出金额（-元）")) {
										retDetail.amount = mapKV.get("支出金额（-元）").replace("+", "").replace("-", "").trim();
									}
									retDetail.cdFlag = "27";
								} else {
									if (mapKV.containsKey("收入金额（+元）")) {
										retDetail.amount = mapKV.get("收入金额（+元）").replace("+", "").replace("-", "").trim();
									}
									retDetail.cdFlag = "22";
								}

								if (mapKV.containsKey("对方账号")) {
									retDetail.oppAct = mapKV.get("对方账号").replace("`", "").trim();
								}
								if (mapKV.containsKey("备注")) {
									retDetail.memo = mapKV.get("备注").replace("`", "").trim();
								}

								retDetail.transState = TransState.Success;

								retAts.writeRetDetail(retDetail);
							} else {
								break;
							}
						}
					} else {
						tmpRespCode = "-1";
						tmpRespInfo = "解压后对账单结果文件内容为空";
					}
				} else {
					tmpRespCode = "-1";
					tmpRespInfo = "支付宝统一收单对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);

		tmpRespHeader[0] = tmpRespCode;
		tmpRespHeader[1] = tmpRespInfo;

		return tmpRespHeader;
	}
}
